package com.zwcl.common.core.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * httpclient
 *
 * @Author kunye
 * @Date 2019/7/23 10:33
 * @Email kunye.guo@wetax.com.cn
 */
@Slf4j
public class HttpClientUtils {

    /**
     * 连接对象
     */
    private static CloseableHttpClient httpClient = null;

    /**
     * 最大连接条数
     */
    private static Integer maxTotal = 20;

    /**
     *
     */
    private static Integer maxPerRoute = 2;

    /**
     * 连接请求超时时间
     */
    private static Integer connectionRequestTimeout = 10000;

    /**
     * 连接时间
     */
    private static Integer connectTimeout = 10000;

    /**
     *
     */
    private static Integer socketTimeout = 10000;

    static {
        PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
                        .build());
        phccm.setMaxTotal(maxTotal);
        phccm.setDefaultMaxPerRoute(maxPerRoute);
        phccm.setValidateAfterInactivity(5000);
        RequestConfig rc = RequestConfig.custom()
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        httpClient = HttpClients.custom()
                .setConnectionManager(phccm)
                .setDefaultRequestConfig(rc)
                .evictIdleConnections(60, TimeUnit.SECONDS)
                .evictExpiredConnections()
                .build();
        log.info("初始化Httpclient成功");
    }

    /**
     * 私有化构造器
     *
     * @return httpClient
     */
    private CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    /**
     * @param url
     * @param method
     * @return
     */
    public static CloseableHttpResponse makeHttpRequest(String url, String method) {
        HttpRequestBase httpRequest = null;
        try {
            if (method.equalsIgnoreCase("POST")) {
                httpRequest = new HttpPost(url);
            } else if (method.equalsIgnoreCase("PATCH")) {
                httpRequest = new HttpPatch(url);
            } else if (method.equalsIgnoreCase("PUT")) {
                httpRequest = new HttpPut(url);
            } else if (method.equalsIgnoreCase("DELETE")) {
                httpRequest = new HttpDelete(url);
            } else {
                httpRequest = new HttpGet(url);
            }
            return httpClient.execute(httpRequest);
        } catch (Exception e) {
            httpRequest.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequest(String url, String method, Map<String, ?>... params) {
        HttpRequestBase httpRequest = null;
        try {
            if (method.equalsIgnoreCase("POST")) {
                httpRequest = getPostRequest(url, params);
            } else if (method.equalsIgnoreCase("PATCH")) {
                httpRequest = getPatchRequest(url, params);
            } else if (method.equalsIgnoreCase("PUT")) {
                httpRequest = getPutRequest(url, params);
            } else if (method.equalsIgnoreCase("DELETE")) {
                httpRequest = getDeleteRequest(url, params);
            } else {
                httpRequest = getGetRequest(url, params);
            }
            return httpClient.execute(httpRequest);
        } catch (Exception e) {
            httpRequest.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequest(String url, Map<String, String> headers, String method, Map<String, ?>... params) {
        HttpRequestBase httpRequest = null;
        try {
            if (method.equalsIgnoreCase("POST")) {
                httpRequest = getPostRequest(url, params);
            } else if (method.equalsIgnoreCase("PATCH")) {
                httpRequest = getPatchRequest(url, params);
            } else if (method.equalsIgnoreCase("PUT")) {
                httpRequest = getPutRequest(url, params);
            } else if (method.equalsIgnoreCase("DELETE")) {
                httpRequest = getDeleteRequest(url, params);
            } else {
                httpRequest = getGetRequest(url, params);
            }
            for (String key : headers.keySet()) {
                httpRequest.setHeader(key, headers.get(key));
            }
            return httpClient.execute(httpRequest);
        } catch (Exception e) {
            httpRequest.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequestByRaw(String url, String text) {
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(text, "UTF-8");
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            httpPost.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequestByRaw(String url, Map<String, String> headers, String text) {
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(text, "UTF-8");
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            for (String key : headers.keySet()) {
                httpPost.setHeader(key, headers.get(key));
            }
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            httpPost.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequestByStream(String url, InputStream inputStream) {
        HttpPost httpPost = new HttpPost(url);
        try {
            InputStreamEntity entity = new InputStreamEntity(inputStream);
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            httpPost.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse makeHttpRequestByStream(String url, Map<String, String> headers, InputStream inputStream) {
        HttpPost httpPost = new HttpPost(url);
        try {
            InputStreamEntity entity = new InputStreamEntity(inputStream);
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            for (String key : headers.keySet()) {
                httpPost.setHeader(key, headers.get(key));
            }
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            httpPost.abort();
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        }
    }

    public static String makeHttpRequestStringResult(String url, String method) {
        CloseableHttpResponse httpResponse = makeHttpRequest(url, method);
        return getStringResult(url, httpResponse);
    }

    public static String makeHttpRequestStringResult(String url, String method, Map<String, ?>... params) {
        CloseableHttpResponse httpResponse = makeHttpRequest(url, method, params);
        return getStringResult(url, httpResponse);
    }

    public static String makeHttpRequestStringResult(String url, Map<String, String> headers, String method, Map<String, ?>... params) {
        CloseableHttpResponse httpResponse = makeHttpRequest(url, headers, method, params);
        return getStringResult(url, httpResponse);
    }

    public static String postString(String url, String text) {
        CloseableHttpResponse httpResponse = makeHttpRequestByRaw(url, text);
        return getStringResult(url, httpResponse);
    }

    public static String postString(String url, Map<String, String> headers, String text) {
        CloseableHttpResponse httpResponse = makeHttpRequestByRaw(url, headers, text);
        return getStringResult(url, httpResponse);
    }

    public static String makeHttpRequestByStreamStringResult(String url, InputStream inputStream) {
        CloseableHttpResponse httpResponse = makeHttpRequestByStream(url, inputStream);
        return getStringResult(url, httpResponse);

    }

    public static String makeHttpRequestByStreamStringResult(String url, Map<String, String> headers, InputStream inputStream) {
        CloseableHttpResponse httpResponse = makeHttpRequestByStream(url, headers, inputStream);
        return getStringResult(url, httpResponse);

    }

    public static String getStringResult(String url, CloseableHttpResponse response) {
        try {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (HttpResponseException e) {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e1) {
                    log.error("error: ", e1);
                    throw new RuntimeException(e);
                }
            }
            log.error("使用Httpclient发送请求失败, url : {}, 请求状态码 : {}", url, e.getStatusCode());
            throw new RuntimeException(e);
        } catch (Exception e) {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e1) {
                    log.error("error: ", e1);
                    throw new RuntimeException(e);
                }
            }
            log.error("使用Httpclient发送请求失败, url : {}", url);
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e1) {
                    log.error("error: ", e1);
                }
            }
        }
    }

    private static HttpGet getGetRequest(String url, Map<String, ?>... params) {
        List<NameValuePair> newParams = constructParams(params);
        String urlParams = URLEncodedUtils.format(newParams, "UTF-8");
        String newUrl = url;
        if (!urlParams.isEmpty()) {
            if (url.contains("?")) {
                if (url.endsWith("?")) newUrl += urlParams;
                else newUrl += "&" + urlParams;
            } else newUrl += "?" + urlParams;
        }
        return new HttpGet(newUrl);
    }

    private static HttpPost getPostRequest(String url, Map<String, ?>... params) {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> newParams = constructParams(params);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(newParams, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("error: ", e);
            throw new RuntimeException(e);
        }
        return httpPost;
    }

    private static HttpPatch getPatchRequest(String url, Map<String, ?>... params) {
        HttpPatch httpPatch = new HttpPatch(url);
        List<NameValuePair> newParams = constructParams(params);
        try {
            httpPatch.setEntity(new UrlEncodedFormEntity(newParams, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("error: ", e);
            throw new RuntimeException(e);
        }
        return httpPatch;
    }

    private static HttpPut getPutRequest(String url, Map<String, ?>... params) {
        HttpPut httpPut = new HttpPut(url);
        List<NameValuePair> newParams = constructParams(params);
        try {
            httpPut.setEntity(new UrlEncodedFormEntity(newParams, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("error: ", e);
            throw new RuntimeException(e);
        }
        return httpPut;
    }

    private static HttpDelete getDeleteRequest(String url, Map<String, ?>... params) {
        List<NameValuePair> newParams = constructParams(params);
        String urlParams = URLEncodedUtils.format(newParams, "UTF-8");
        String newUrl = url;
        if (!urlParams.isEmpty()) {
            if (url.contains("?")) {
                if (url.endsWith("?")) newUrl += urlParams;
                else newUrl += "&" + urlParams;
            } else newUrl += "?" + urlParams;
        }
        return new HttpDelete(newUrl);
    }

    private static List<NameValuePair> constructParams(Map<String, ?>... params) {
        List<NameValuePair> newParams = new ArrayList<NameValuePair>();
        if (params != null && params.length > 0) {
            for (Map<String, ?> param : params) {
                if (param != null) {
                    for (String key : param.keySet()) {
                        if (param.get(key) instanceof String[]) {
                            String[] val = (String[]) param.get(key);
                            for (int i = 0; i < val.length; ++i) newParams.add(new BasicNameValuePair(key, val[i]));
                        } else newParams.add(new BasicNameValuePair(key, String.valueOf(param.get(key))));
                    }
                }
            }
        }
        return newParams;
    }

    public void close() {
        if (httpClient != null) {
            try {
                httpClient.close();
                log.info("关闭Httpclient成功");
            } catch (IOException e) {
                log.error("error : ", e);
            }
        }
    }

    public void setMaxTotal(Integer maxTotal) {
        this.maxTotal = maxTotal;
    }

    public void setMaxPerRoute(Integer maxPerRoute) {
        this.maxPerRoute = maxPerRoute;
    }

    public void setConnectionRequestTimeout(Integer connectionRequestTimeout) {
        this.connectionRequestTimeout = connectionRequestTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }
}
